package c17网络编程;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class 多线程ServerSocket {
	static final int SERVER_PORT = 8080;
	//服务端socket，用这个来监听客户端连接
	static ServerSocket serverSocket;

	public static void main(String[] args) throws IOException {
		serverSocket = new ServerSocket(SERVER_PORT);
		try {
			System.err.println("服务端socket开始监听客户端连接...");
			while (true) {
				Socket clientSocket = serverSocket.accept();
				try {
					new TalkBackThread(clientSocket);
				} catch (IOException e) {
					clientSocket.close();
				}
			}
		} finally {
			serverSocket.close();
		}
	}

	//回复客户端信息的线程
	static class TalkBackThread extends Thread {
		//客户端socket
		private Socket clientSocket;
		//客户端信息
		private String clientInfo;
		//读取客户端信息的输入流
		private BufferedReader in;
		//往取客户端发送信息的输出流
		private PrintWriter out;

		public TalkBackThread(Socket socket) throws IOException {
			clientSocket = socket;
			clientInfo = clientSocket.getInetAddress() + ":" + clientSocket.getPort();
			in = new BufferedReader(
					new InputStreamReader(clientSocket.getInputStream()));
			out = new PrintWriter(new BufferedWriter(
					new OutputStreamWriter(clientSocket.getOutputStream())), true);
			//开启线程
			this.start();
		}

		@Override
		public void run() {
			try {
				System.err.println("接收到来自客户端" + clientInfo + "的连接...");
				out.println("欢迎连接到本服务器，请开始输入信息：");
				String str = null;
				while ((str = in.readLine()) != null) {
					if (str.equals("end")) {
						break;
					}
					System.err.println("客户端" + clientInfo + "说：" + str);
					out.println("success");
				}
				System.err.println("客户端" + clientInfo + "已下线...");
				clientSocket.close();
				out.close();
				in.close();
			} catch (IOException e) {
				System.err.println("客户端" + clientInfo + "已下线...");
			} finally {

			}
		}
	}

}
